package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报表控制实现层
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 1 查询订单，条件 状态是已完成的 2.x轴日期，按天拼出来 3.按每天日期去查询数据
        //拼接日期，根据前端给定开始日期开始拼接，一直到前端给定的end日期结束
        //11-10 11-17
        //11-10 11-11 11-12 .... 11-17
        List<LocalDate> dateList = getDateList(begin, end);
        //遍历日期集合，查询数据
        //11-10 00:00:00 -  11-10 23:59:59
        //11-10,11-11,11-12
        //100.120
        //金额集合
        List<Double> amountList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //00:00:00
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //23:59:59
            LocalDateTime endTime = LocalDateTime.of(localDate,LocalTime.MAX);
            //查询订单数据，条件，订单状态，日期时间
            Map params = new HashMap();
            params.put("satus", Orders.COMPLETED);
            params.put("begin",beginTime);
            params.put("end",endTime);
            //调用mapper查询数据
            Double amount = orderMapper.sumByMap(params);
            //如果返回的是null，要添加0
            amountList.add(amount == null ? 0:amount);
        }
        //拼接返回值
        TurnoverReportVO reportVO = new TurnoverReportVO();
        //给定集合，按照指定的方式拼接，返回字符串
        //日期集合
        String joinDateList= StringUtils.join(dateList,",");
        //金额集合
        String joinAmountLIst = StringUtils.join(amountList,",");
        reportVO.setDateList(joinDateList);
        reportVO.setTurnoverList(joinAmountLIst);
        return reportVO;
    }

    /**
     * 获取用户数量信息
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin,end);
        //根据传入的时间范围，查询每天用户数量的变化
        //每天的用户总量 = 查询当前结束日期之前的所有用户数量
        //11 10  12新增了2个12  13新增了两个 14
        //新增的用户数量 = 查询每天的用户数量
        //12 2
        //用户总量集合
        List<Integer> totalUserList = new ArrayList<>();
        //新增用户集合
        List<Integer> newUserList = new ArrayList<>();
        //遍历日期范围集合，查询每天的数据
        for (LocalDate localDate : dateList) {
            //00:00:00
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            //23:59:59
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //每天用户新增数量
            Integer userCount = getUserCountByMap(beginTime,endTime);
            newUserList.add(userCount);
            //用户总量
            Integer totalCount = getUserCountByMap(null,endTime);
            totalUserList.add(totalCount);
        }

        UserReportVO userReportVO = new UserReportVO();
        //日期
        String joinDateList = StringUtils.join(dateList,",");
        //新增用户集合
        String joinNewUserList = StringUtils.join(newUserList, ",");
        //用户总量
        String joinTotalUserList = StringUtils.join(totalUserList, ",");
        userReportVO.setDateList(joinDateList);
        userReportVO.setNewUserList(joinNewUserList);
        userReportVO.setTotalUserList(joinTotalUserList);
        return userReportVO;
    }

    private Integer getUserCountByMap(LocalDateTime beginTime,LocalDateTime endTime){
        Map params = new HashMap();
        params.put("satus", Orders.COMPLETED);
        params.put("begin",beginTime);
        params.put("end",endTime);
        //每天用户新增数量
        return userMapper.countByMap(params);
    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //如果开始日期和结束日期一致，那么跳出循环
        while (!begin.equals(end)){
            //把开始时间+1
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 订单数量统计
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //有效订单 已完成的
        //总订单 不需要查询状态的所有订单
        //按照前端传递的日期区间，按每天的建个查询
        List<LocalDate> dateList = getDateList(begin,end);
        //有效订单数
        List<Integer> validOrderCountList= new ArrayList<>();
        //订单总数量
        List<Integer> orderCountList = new ArrayList<>();
        //获取订单数量
        for (LocalDate localDate : dateList) {
            //完成按照每天的日期查询
            //00:00:00
            LocalDateTime beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            //23:59:59
            LocalDateTime endTime = LocalDateTime.of(localDate,LocalTime.MAX);
            //调用mapper查询 需要查询有效订单数
            Integer validCount = getOrderCountByTime(beginTime,endTime,Orders.COMPLETED);
            validOrderCountList.add(validCount);
            //订单总数量
            Integer orderCount = getOrderCountByTime(beginTime,endTime,null);
            orderCountList.add(orderCount);
            //total+=totalCount
            //查询订单数
        }
        //订单累加 有效订单 总订单数
        //1 2 3 4
        //有效订单 (1,2)->1+2 (3,4)->()
        Integer validCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单总数量
        Integer totalCount = orderCountList.stream().reduce(Integer::sum).get();
        //订单完成率 有效订单数量/总订单数量
        Double orderCompletionRate =0.0;
        if (totalCount != 0){
            orderCompletionRate = validCount.doubleValue()/totalCount;
        }
        String joinDateList = StringUtils.join(dateList,",");
        String joinValidOrderCountList = StringUtils.join(validOrderCountList,",");
        String joinOrderCountList = StringUtils.join(orderCountList,",");
        OrderReportVO orderReportVO = new OrderReportVO();
        //订单完成率
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        //订单总数量
        orderReportVO.setTotalOrderCount(totalCount);
        //有效订单
        orderReportVO.setValidOrderCount(validCount);
        //日期
        orderReportVO.setDateList(joinDateList);
        //有效订单集合
        orderReportVO.setValidOrderCountList(joinValidOrderCountList);
        //总订单集合
        orderReportVO.setOrderCountList(joinOrderCountList);
        return orderReportVO;
    }

    private Integer getOrderCountByTime(LocalDateTime beginTime,LocalDateTime endTime, Integer status){
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin",beginTime);
        map.put("end",endTime);
        //每天用户新增数量
        return orderMapper.countByMap(map);
    }

    //查询指定时间区间内的销量排名

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    //导出数据报表

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //查询近30天的数据
        //开始日期 = 前30
        LocalDate beginDate = LocalDate.now().minusDays(30);
        //前30天最小时间
        LocalDateTime beginDateMinTime = LocalDateTime.of(beginDate,LocalTime.MIN);
//        LocalDateTime with = LocalDateTime.now().minusDays(30).with(LocalTime.MIN);
        //结束日期 = 前一天
        LocalDate endDate = LocalDate.now().minusDays(1);
        //结束日期的最大时间
        LocalDateTime endDateMaxTime = LocalDateTime.of(endDate,LocalTime.MAX);
//        LocalDateTime with =LocalDateTime.now().minusDays(1).with(LocalTime.MAX);
        //获取数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginDateMinTime, endDateMaxTime);
        //加载模板
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("template/template.xlsx");

        //根据模板创建excel
        try {
            //工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(resourceAsStream);
            //拿到sheet页
            XSSFSheet sheet = workbook.getSheetAt(0);
            //赋值日期
            sheet.getRow(1).getCell(1).setCellValue(beginDate + "至" + endDate);
            //获取第四行
            //营业额
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //获取第五航
            //有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //订单明细
            for (int i = 0; i < 30; i++) {
                //获取日期
                beginDate = beginDate.plusDays(1);
                //当天最小时间
                LocalDateTime minTime = LocalDateTime.of(beginDate, LocalTime.MIN);
                LocalDateTime maxTime = LocalDateTime.of(beginDate, LocalTime.MAX);
                //调用接口查询
                //每日数据
                BusinessDataVO data = workspaceService.getBusinessData(minTime, maxTime);
                XSSFRow row = sheet.getRow(7 + i);
                //日期
                row.getCell(1).setCellValue(beginDate.toString());
                //营业额
                row.getCell(2).setCellValue(data.getTurnover().toString());
                //有效订单
                row.getCell(3).setCellValue(data.getValidOrderCount().toString());
                //订单完成率
                row.getCell(4).setCellValue(data.getOrderCompletionRate().toString());
                //客单价
                row.getCell(5).setCellValue(data.getUnitPrice().toString());
                //新增用户数
                row.getCell(6).setCellValue(data.getNewUsers().toString());
            }
            //下载excel
            ServletOutputStream outputStream = response.getOutputStream();
            //通过浏览器下载
            workbook.write(outputStream);

            outputStream.flush();
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
